﻿using AutoMapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Implement;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Read.Apis.Application.Command.Rolees;
using MediatR;

namespace Management.Systeam.Read.Apis.Application.CommandHandler.Rolees
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        IBaseRepository<Users> Users;
        IBaseRepository<RoleUser> RoleUser;
        IBaseRepository<Role> Role;
        IMapper mapper;
        DatabaseContext db;
        public AddRoleCommandHandler(IBaseRepository<Users> Users, IBaseRepository<RoleUser> RoleUser, IBaseRepository<Role> Role, IMapper mapper, DatabaseContext db)
        {
            this.Users = Users;
            this.RoleUser = RoleUser;
            this.Role = Role;
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> apiResult = new ApiResult<int>();
            try
            {
                var Chename = db.SqlSugar.Queryable<Role>().Where(c => c.Role_Name == request.Role_Name
 && !c.IsDel).Count();
                if (Chename > 0)
                {
                    apiResult.Code = ApiEnum.error;
                    apiResult.Message = "该角色已存在";
                    apiResult.Data = 0;
                    return apiResult;
                }
                var Nid = 1;
                var fistlist = db.SqlSugar.Queryable<Role>().OrderByDescending(c => c.Role_Code).First();
                if (fistlist != null)
                {
                    Nid = Convert.ToInt32(fistlist.Role_Code.Replace("Sys_", ""));
                    Nid++;
                }


                var model = mapper.Map<Role>(request);
                model.Role_Code = "Sys_" + Nid.ToString().PadLeft(6, '0');
                model.Role_CreateTime = DateTime.Now;
                int r = Role.InsertAsync(model).Result;
                if (r > 0)
                {
                    apiResult.Code = ApiEnum.success;
                    apiResult.Message = "添加成功";
                }

            }
            catch (Exception ex)
            {
                apiResult.Code = ApiEnum.error;
                apiResult.Message = ex.Message;

            }
            return apiResult;
        }
    }
}
